import { setToken, getToken, delToken } from '@/utils/storage'
import { getAvatarStorage, setAvatarStorage, delAvatarStorage, getUserName, setUserName, delUserName } from '@/utils/avatarStorage'
import { login } from '@/api/user'
import { message } from 'element-ui'
import router from '@/router'

export default {
  namespaced: true,
  state () {
    return {
      token: getToken() || '',
      avatarSrc: getAvatarStorage() || require('@/assets/images/head.png'),
      uname: getUserName() || ''
    }
  },
  mutations: {
    setUserToken (state, newToken) {
      state.token = newToken
      setToken(newToken)
    },
    logout (state) {
      state.token = ''
      delToken()
      delAvatarStorage()
      delUserName()
    },
    setUserAvatar (state, newAvatar) {
      if (newAvatar) {
        state.avatarSrc = newAvatar
        setAvatarStorage(newAvatar)
      }
    },
    getUserName (state, newName) {
      state.uname = newName
      setUserName(newName)
    }
  },
  actions: {
    async loginAction (context, obj) {
      const res = await login(obj)
      if (res.message !== '登录成功！') {
        message.error(res.message)
        return
      }

      message.success('登录成功')
      router.push('home')
      context.commit('setUserToken', res.token)
    }
  },
  getters: {}
}
